package com.gm.app.data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.gm.app.model.Register;

public class RegisterDAO extends EntityDAO {

	private static RegisterDAO dao = null;

	public static RegisterDAO get() {
		if (dao == null) {
			dao = new RegisterDAO();
		}
		return dao;
	}

	public static TypedQuery<? extends Register> search(String name,
			String address, String country, String comments, Integer start,
			Integer page) {
		return RegisterDAO.get().search(name, address, country, comments,
				start, page, Register.class);
	}

	public <T extends Register> TypedQuery<T> search(String name,
			String address, String country, String comments, Integer start,
			Integer page, Class<T> example) {
		StringBuilder query = new StringBuilder();
		query.append("select reg from " + example.getSimpleName() + " reg ");
		List<String> params = new ArrayList<String>();
		boolean first = true;
		if (name != null && name.length() > 0) {
			Map<StringBuilder, List<String>> map = getParts(name,
					"UPPER(reg.contact.name) like UPPER(?)", first);
			for (Entry<StringBuilder, List<String>> e : map.entrySet()) {
				if (first)
					query.append("where ");
				query.append(e.getKey().toString());
				params.addAll(e.getValue());
				first = false;
			}
		}
		if (address != null && address.length() > 0) {
			Map<StringBuilder, List<String>> map = getParts(address,
					"UPPER(reg.address.description) like UPPER(?)", first);
			for (Entry<StringBuilder, List<String>> e : map.entrySet()) {
				if (first)
					query.append("where ");
				query.append(e.getKey().toString());
				params.addAll(e.getValue());
				first = false;
			}
		}
		if (country != null && country.length() > 0) {
			Map<StringBuilder, List<String>> map = getParts(country,
					"UPPER(reg.contact.country.description) like UPPER(?)",
					first);
			for (Entry<StringBuilder, List<String>> e : map.entrySet()) {
				if (first)
					query.append("where ");
				query.append(e.getKey().toString());
				params.addAll(e.getValue());
				first = false;
			}
		}
		if (comments != null && comments.length() > 0) {
			Map<StringBuilder, List<String>> map = getParts(comments,
					"UPPER(reg.comments) like UPPER(?)", first);
			for (Entry<StringBuilder, List<String>> e : map.entrySet()) {
				if (first)
					query.append("where ");
				query.append(e.getKey().toString());
				params.addAll(e.getValue());
				first = false;
			}
		}
		return pagedQuery(query.toString(), start, page, example,
				params.toArray());

	}

}
